package com.qcby.aopdemo0709.controller;

import com.qcby.aopdemo0709.service.SubmissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;


@RestController
public class SubmissionController {

    @Autowired
    private SubmissionService submissionService;

    private static Jedis jedis = new Jedis("localhost",6379);
    private String lock = "lock";
    private String lockValue = "locked";
    private int gqsj = 5;


    @PostMapping("/submit")
    public void handleSubmitForm(@RequestParam String name, @RequestParam int age) {
        String lockKey = "lastSubmitTime:" + name; // 假设锁键与用户名相关
        long currentTimeMillis = System.currentTimeMillis(); // 当前时间戳（毫秒）
        long allowedIntervalMillis = 5000; // 允许的提交间隔，5秒（毫秒）

        // 从Redis中获取上次提交的时间戳
        String lastSubmitTimeStr = jedis.get(lockKey);
        long lastSubmitTimeMillis = lastSubmitTimeStr != null ? Long.parseLong(lastSubmitTimeStr) : 0;

        // 检查上次提交时间是否在当前时间的前5秒内
        if (currentTimeMillis - lastSubmitTimeMillis < allowedIntervalMillis) {
            // 如果在5秒内，则认为是重复提交
            System.out.println("禁止重复提交，请稍后再试");
            return;
        }

        // 执行提交操作
        try {
            submissionService.insert(name, age);
            System.out.println("提交成功");

            // 更新Redis中的上次提交时间戳
            jedis.setex(lockKey, allowedIntervalMillis / 1000 + 1, String.valueOf(currentTimeMillis));
            // 注意：这里使用setex设置了过期时间，比允许的间隔多1秒作为缓冲，确保不会因为时间精度问题导致无法提交
        } catch (Exception e) {
            // 处理可能的异常
            e.printStackTrace();
        }
    }
}


